package com.xzsoft.gdwz.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import xz.facade.user.model.Result;
import ch.qos.logback.classic.Logger;

import com.xzsoft.gdwz.model.OrderHeader;
import com.xzsoft.gdwz.model.OrderLine;
import com.xzsoft.gdwz.model.TrdPsEmInfLog;
import com.xzsoft.gdwz.services.JdOrderService;
import com.xzsoft.gdwz.services.OrderService;
import com.xzsoft.gdwz.services.RefreshTokenServices;
import com.xzsoft.gdwz.services.TrdPsEmInfLogService;

@Controller
@RequestMapping("/order")
public class OrderController {
	
	@Autowired
	private RefreshTokenServices refreshTokenServices;
	
	@Autowired
	private JdOrderService jdOrderService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private TrdPsEmInfLogService trdPsEmInfLogService;
	
	@RequestMapping(value="/selectJdOrder")
	public void selectJdOrder(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");  
		DateTime dateTime = new DateTime();
		String createdate = dateTime.toString("yyyy-MM-dd HH:mm:ss");
		List list = new ArrayList();
		for(int j = 0 ; j<2 ;j++){
			String orderId = UUID.randomUUID().toString();
			Map map = new HashMap();
			map.put("jdOrderId", orderId);
			map.put("state", 0);
			map.put("type", 1);
			map.put("orderPrice", 1000);
			map.put("freight", 15);
			map.put("pOrder", -1);
			map.put("orderState", 1);
			map.put("submitState", 0);
			map.put("username", "国电汉川发电有限公司");
			map.put("createorderTime", createdate);
			List orderLine = new ArrayList();
			for(int i=0;i<3;i++){
				Map line = new HashMap();
				line.put("skuId",UUID.randomUUID().toString());
				line.put("name", "商品"+getRandomString(10));
				line.put("skunum", getRandomInt(1,10));
				line.put("price", getRandomInt(50,200));
				line.put("nakedPrice", getRandomInt(50,200));
				line.put("createdate", createdate);
				orderLine.add(line);
			}
			map.put("sku", orderLine);
			//response.getWriter().println(JSONObject.fromObject(map));
			list.add(map);
		}
		//JSONObject obj = JSONObject.fromObject(list);
		JSONArray array  = JSONArray.fromObject(list);
		System.out.println(array.toString());
		response.getWriter().println(array.toString());
		response.getWriter().flush();  
		response.getWriter().close(); 
	}
	
	@RequestMapping(value="/deliverOrder")
	public void deliverOrder(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");  
		DateTime dateTime = new DateTime();
		String createdate = dateTime.toString("yyyy-MM-dd HH:mm:ss");
		List list = new ArrayList();
		for(int j = 0 ; j<100 ;j++){
			String orderId = UUID.randomUUID().toString();
			OrderHeader oh = new OrderHeader();
			oh.setAddress("北京市昌平区北七家镇");
			oh.setCreateBy("Gdcyhcdyfd@qq.com");
			oh.setCreateByPhone("13808684178");
			oh.setCreateDate(createdate);
			oh.setEcommerceName("DL");
			oh.setEcommerceOrderId(orderId);
			oh.setInqAmount("1000");
			List lines = new ArrayList();
			for(int i=0;i<3;i++){
				OrderLine ol = new OrderLine();
				ol.setEcommerceSkuId(UUID.randomUUID().toString());
				ol.setMtName("商品"+getRandomString(10));
				ol.setMtCode(getRandomString(10));
				ol.setReqBrand(getRandomString(8));
				ol.setInqPrice(getRandomInt(50,200)+"");
				ol.setReqQuantity(getRandomInt(1,10)+"");
				ol.setCreationDate(createdate);
				ol.setCreatedBy("Gdcyhcdyfd@qq.com");
				ol.setReqSpec(getRandomString(20));
				ol.setReqMaterial(getRandomString(20));
				ol.setReqBrand(getRandomString(15));
				ol.setReqMaterial(getRandomString(12));
				ol.setReqUnit("个");
				ol.setReqModel(getRandomString(12));
				ol.setPrName(getRandomString(7));
				lines.add(ol);
			}
			oh.setOrderLines(lines);
			list.add(oh);
		}
		JSONArray array  = JSONArray.fromObject(list);
		
		
	}
	
	public static String getRandomString(int length) { //length表示生成字符串的长度
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }   
		
	 public static int getRandomInt(int max,int min){		
        Random random = new Random();
        int s = random.nextInt(max)%(max-min+1) + min;
        return s;
	 }
	 
	 /**
	  * 接受订单信息
	  * @param request
	  * @param response
	 * @throws IOException 
	  */
	 @RequestMapping(value="/reciveOrder",produces="text/html;charset=UTF-8")
	 public void reciveOrder(HttpServletRequest request,HttpServletResponse response) throws IOException{
		 String orderInfo = request.getParameter("order_info");
		 Result result = new Result();
		 String ename = null;
		 //解析jasonarray 
		 JSONArray resultArray = null;
		try {
			resultArray = JSONArray.fromObject(orderInfo);
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0011");
			result.setResultMessage("JSONArray格式不正確！");
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return;
		}
		 try {
			//获取电商名称
			ename= resultArray.getJSONObject(0).getString("INQ_SOURCE");			
			orderService.saveOrder(resultArray);
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0012");
			result.setResultMessage(e.getMessage());
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			//保存日志
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName(ename);
			log.setErrorMsg(e.getMessage());
			log.setHasRecieve("0");
			if(e.getMessage().contains("|")){
				String orderId = e.getMessage().split("|")[1];
				log.setOrderId(orderId);
				log.setErrorMsg(e.getMessage().split("|")[0]);
			}
			log.setOrderInfo(resultArray.toString());
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
			return;
		}
			result.setResult("");
			result.setResultCode("");
			result.setResultMessage("");
			result.setSuccess(true);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
	 }
}
